package com.vf.cloud.paas.app.master.api.scene.service.impl;

import java.util.LinkedList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.paas.app.master.api.scene.service.ISceneLayer;
import com.vf.cloud.paas.app.master.common.domain.SceneActor;
import com.vf.cloud.paas.app.master.common.domain.SceneLayer;
import com.vf.cloud.paas.app.master.common.vo.scene.SceneTree;
import com.vf.cloud.paas.app.master.common.vo.scene.SceneTreeParam;

@Service
public class SceneLayerImpl implements ISceneLayer {

	public List<SceneTree> getTree(SceneTreeParam param) {
		return getChildrens(param.getPid(), param.getSceneid(), param.isGetActor());
	}

	public List<SceneTree> getChildrens(String pid, String sceneid, boolean isGetActor) {
		List<SceneLayer> layers = SceneLayer.dao.find("select * from master_scene_layer where pid=? order by sort asc ",
				pid);
		List<SceneTree> sceneTrees = new LinkedList<SceneTree>();
		SceneTree sceneTree;
		for (SceneLayer layer : layers) {
			sceneTree = new SceneTree();
			sceneTree.setId(layer.getId());
			sceneTree.setLabel(layer.getLabel());
			sceneTree.setType("Layer");
			sceneTree.setIsShow(layer.getIsShow());
			sceneTree.setPid(layer.getPid());

			List<SceneTree> children = new LinkedList<SceneTree>();
			if (isGetActor)
				children.addAll(getActors(layer.getId()));
			children.addAll(getChildrens(layer.getId(), sceneid, isGetActor));
			sceneTree.setChildren(children);
			sceneTrees.add(sceneTree);
		}
		return sceneTrees;
	}

	public List<SceneTree> getActors(String pid) {
		List<SceneActor> layers = SceneActor.dao
				.find("select * from master_scene_actor where layer_id=? order by sort asc ", pid);
		List<SceneTree> sceneTrees = new LinkedList<SceneTree>();
		SceneTree sceneTree;
		for (SceneActor actor : layers) {
			sceneTree = new SceneTree();
			sceneTree.setId(actor.getId());
			sceneTree.setLabel(actor.getName());
			sceneTree.setType("Actor");
			sceneTree.setPid(pid);
			sceneTree.setIsShow(actor.getIsShow());
			sceneTree.setActorType(actor.getType());
			sceneTrees.add(sceneTree);
		}
		return sceneTrees;
	}

	@Override
	public void delete(String id) {
		Db.delete("delete from " + SceneActor.TABLE_NAME + " where layer_id=?", id);
		SceneLayer.dao.deleteById(id);
		deleteChildrens(id);
	}

	private void deleteChildrens(String pid) {
		List<SceneLayer> layers = SceneLayer.dao.find("select * from master_scene_layer where pid=? order by sort asc ",
				pid);
		for (SceneLayer layer : layers) {
			deleteChildrens(layer.getId());
			layer.delete();
		}
	}

}
